import {computed, reactive} from "@peryl/react-compose";
import {buildAssetsPath} from "./buildAssetsPath";

export function useDemoData(filePath: string, config?: { formatData?: (data: any[]) => any[], onLoad?: (data: any[]) => void }) {
  const state = reactive({
    data: [] as any[],
    loading: true,
  });

  fetch(buildAssetsPath(filePath)).then(async resp => {
    let newData = await resp.json();
    if (config?.formatData) {
      newData = config.formatData(newData);
    }
    config?.onLoad?.(newData);
    state.data = newData;
    state.loading = false;
  });

  const data = computed(() => state.data.slice(0, -2));
  const summaryData = computed(() => state.data.slice(state.data.length - 2));

  return {
    get data() {return data.value;},
    get summaryData() {return summaryData.value;},
    get loading() {return state.loading;},
  };
}
